//
//  SentencePlayCardCell.swift
//  Game
//
//  Created by GitHub Copilot on 2025/9/12.
//

import UIKit
import SnapKit

class SentencePlayCardCell: UITableViewCell {
    static let reuseIdentifier = "SentencePlayCardCell"

    private let cardView = UIView()
    private let titleLabel = UILabel()
    private let resultImageView = UIImageView()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setup()
    }
    required init?(coder: NSCoder) { super.init(coder: coder); setup() }

    private func setup() {
        selectionStyle = .none
        backgroundColor = .clear
        self.tintColor = .white
        
        // 渐变背景设置
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [
            UIColor(red: 1.0, green: 0.847, blue: 0.655, alpha: 1.0).cgColor,  // 温暖的浅橙色
            UIColor(red: 0.992, green: 0.659, blue: 0.498, alpha: 1.0).cgColor // 珊瑚色
        ]
        gradientLayer.locations = [0.0, 1.0]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 1, y: 1)
        cardView.layer.insertSublayer(gradientLayer, at: 0)
        
        // 添加阴影效果
        cardView.layer.shadowColor = UIColor.black.cgColor
        cardView.layer.shadowOffset = CGSize(width: 0, height: 4)
        cardView.layer.shadowRadius = 8
        cardView.layer.shadowOpacity = 0.2
        
        // 添加内阴影效果增强立体感
        let innerShadow = CALayer()
        innerShadow.frame = cardView.bounds
        innerShadow.backgroundColor = UIColor.white.withAlphaComponent(0.1).cgColor
        innerShadow.shadowColor = UIColor.black.cgColor
        innerShadow.shadowOffset = CGSize(width: 0, height: 2)
        innerShadow.shadowOpacity = 0.2
        innerShadow.shadowRadius = 3
        cardView.layer.addSublayer(innerShadow)
        
        // 保持原有设置
        cardView.borderSet(.white.withAlphaComponent(0.3), 1)
        cardView.circular5()
        contentView.addSubview(cardView)
        
        // 原有标签设置
        titleLabel.font = UIFont.boldSystemFont(ofSize: 28)
        titleLabel.textColor = .white
        titleLabel.numberOfLines = 0
        cardView.addSubview(titleLabel)
        
        // 确保渐变层大小随cardView更新
        cardView.layoutSubviews()
        gradientLayer.frame = cardView.bounds

        resultImageView.contentMode = .scaleAspectFit
        resultImageView.isHidden = true
        cardView.addSubview(resultImageView)

        cardView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(6)
            make.bottom.equalToSuperview().offset(-6)
            make.left.equalToSuperview().offset(6)
            make.right.equalToSuperview().offset(-6)
        }

        resultImageView.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-8)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 50, height: 50))
        }

        titleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(10)
            make.top.equalToSuperview().offset(10)
            make.bottom.equalToSuperview().offset(-10)
            make.right.equalToSuperview().offset(-10)
        }
    }
    
    public static func getMaxCellHeight(screenW:CGFloat,items:[SentenceItem])->CGFloat{
        var maxCellH:CGFloat = 0
        let maxW:CGFloat = screenW - 2*6 - 2*10 - 60
        
        for item in items {
            let titleH = item.topic.boundingRect(with: CGSize(width: maxW, height: 200), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font:UIFont.boldSystemFont(ofSize: 28)], context: nil).height
            
            let answerH = item.answer.boundingRect(with: CGSize(width: maxW, height: 200), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font:UIFont.boldSystemFont(ofSize: 28)], context: nil).height
            
            maxCellH = max(maxCellH, titleH)
            maxCellH = max(maxCellH, answerH)
        }
        print("计算cell高度:\(maxCellH)")
        return maxCellH + 40
    }
    
    //更新左边列表
    public func updateUILeft(item: SentenceItem,index:Int){
        titleLabel.text = item.topic
        resultImageView.isHidden = true
        
    }
    
    //更新右边列表
    public func updateUIRight(item: SentenceItem,index:Int){
        titleLabel.text = item.answer
        resultImageView.isHidden = true
    }
    
    public func onCheckAndShow(index:Int,isCorrect: Bool){
        
        resultImageView.image = isCorrect ? UIImage(named: "正确") : UIImage(named: "错误")
        resultImageView.tintColor = isCorrect ? .systemGreen : .systemRed
        
        resultImageView.isHidden = false
        resultImageView.alpha = 0
        
        let delay = TimeInterval(index) * 0.50
        DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
            UIView.animate(withDuration: 0.5, animations: {[weak self]in
                guard let `self` = self else { return }
                self.resultImageView.alpha = 1
                self.resultImageView.transform = .identity
            })
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        if let gradientLayer = cardView.layer.sublayers?.first as? CAGradientLayer {
            gradientLayer.frame = cardView.bounds
        }
        
        // 查找拖拽排序按钮并修改其颜色
        if isEditing {
            for subview in subviews {
                if String(describing: subview.classForCoder) == "UITableViewCellReorderControl" {
                    for controlSubview in subview.subviews {
                        if let imageView = controlSubview as? UIImageView {
                            imageView.tintColor = .white  // 设置拖拽按钮颜色
                            imageView.image = UIImage(named: "排序_白色")
                        }
                    }
                }
            }
        }
    }
}
